package com.liushuo.view;

import com.liushuo.VO.AddExerciseSetVO;
import com.liushuo.controller.ExerciseSetController;
import com.liushuo.controller.MistakeController;
import com.liushuo.entity.ExerciseSet;
import com.liushuo.entity.Question;
import com.liushuo.util.ThreadLocalUtil;

import javax.swing.*;
import javax.swing.Timer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import java.util.List;

public class GeneralUI extends JFrame{
    private final JTextField totalQuestionField;
    private final JTextField questionsWithParenthesesField;
    private final JComboBox gradeLevelComboBox;
    private final JScrollPane scrollPane;
    private final JLabel timerLabel = new JLabel("--:--:--");
    private final JButton generateButton;
    private final JButton clearButton;
    private final JButton viewAnswersButton;
    private final JButton timerButton;
    private final JButton importButton;
    private final JButton exportButton;
    private Timer timer;
    private int selectedMinutes;
    private Boolean isTimerRunning = false;
    private boolean isFlashing = false;
    private Timer flashTimer;


    private List<Question> questions;
    private ExerciseSet exerciseSet;
    private List<JPanel> questionPanels;
    private List<JTextField> answerFields;
    private List<JLabel> resultLabels;
    private final JLabel accuracyLabel;

    private final ExerciseSetController exerciseSetController = new ExerciseSetController();
    private final MistakeController mistakeController = new MistakeController();

    private final String userId = ThreadLocalUtil.getUserId();

    public GeneralUI() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                 | UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }

        Font font = new Font("微软雅黑", Font.PLAIN, 20);

        setTitle("口算练习器-练习模式");

        setBackground(Color.CYAN);
        setBounds(600, 400, 1000, 800);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        JPanel inputPanel = new JPanel();

        JLabel Label1 = new JLabel("总题数：");
        Label1.setFont(font);
        inputPanel.add(Label1);
        totalQuestionField = new JTextField();
        totalQuestionField.setColumns(3);
        totalQuestionField.setFont(font);
        totalQuestionField.setText("10");
        inputPanel.add(totalQuestionField);

        JLabel Label2 = new JLabel("括号题数：");
        Label2.setFont(font);
        inputPanel.add(Label2);
        questionsWithParenthesesField = new JTextField();
        questionsWithParenthesesField.setColumns(3);
        questionsWithParenthesesField.setFont(font);
        questionsWithParenthesesField.setText("0");
        inputPanel.add(questionsWithParenthesesField);

        JLabel Label3 = new JLabel("年级: ");
        Label3.setFont(font);
        inputPanel.add(Label3);
        gradeLevelComboBox = new JComboBox<>(new String[]{"1", "2", "3", "4", "5", "6"});
        gradeLevelComboBox.setFont(font);
        gradeLevelComboBox.setSelectedIndex(1);
        gradeLevelComboBox.addActionListener(new GeneralUI.GradeLevelComboBoxListener());
        inputPanel.add(gradeLevelComboBox);

        generateButton = new JButton("生成题目");
        generateButton.setFont(font);
        generateButton.addActionListener(new GeneralUI.GenerateButtonListener());
        inputPanel.add(generateButton);


        clearButton = new JButton("清空题目");
        clearButton.setFont(font);
        clearButton.addActionListener(new GeneralUI.ClearButtonListener());
        inputPanel.add(clearButton);

        JButton checkButton = new JButton("批改答案");
        checkButton.setFont(font);
        checkButton.addActionListener(new GeneralUI.CheckButtonListener());
        inputPanel.add(checkButton);

        JPanel timerPanel = new JPanel();
        JLabel timerTitleLabel = new JLabel("计时：");
        timerTitleLabel.setFont(font);
        timerPanel.add(timerTitleLabel);
        timerLabel.setFont(font);
        timerPanel.add(timerLabel);

        inputPanel.add(timerPanel);

        add(inputPanel, BorderLayout.NORTH);

        JPanel questionPanel = new JPanel();
        questionPanel.setBackground(Color.CYAN);
        questionPanel.setLayout(new BoxLayout(questionPanel, BoxLayout.Y_AXIS));

        scrollPane = new JScrollPane(questionPanel);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        add(scrollPane, BorderLayout.CENTER);

        // 右答案框
        JPanel rightPanel = new JPanel();
        rightPanel.setBackground(Color.YELLOW);
        rightPanel.setPreferredSize(new Dimension(200, 0));
        rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
        rightPanel.setBorder(BorderFactory.createEmptyBorder(20, 10, 20, 10));

        viewAnswersButton = new JButton("查看答案");
        viewAnswersButton.setFont(font);
        viewAnswersButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        viewAnswersButton.setMaximumSize(new Dimension(180, 40));
        viewAnswersButton.addActionListener(new GeneralUI.ViewAnswersButtonListener());
        rightPanel.add(viewAnswersButton);
        rightPanel.add(Box.createVerticalStrut(10));

        timerButton = new JButton("计时模式");
        timerButton.setFont(font);
        timerButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        timerButton.setMaximumSize(new Dimension(180, 40));
        timerButton.addActionListener(new GeneralUI.TimerButtonListener());
        rightPanel.add(Box.createVerticalStrut(10));
        rightPanel.add(timerButton);


        importButton = new JButton("导入题目");
        importButton.setFont(font);
        importButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        importButton.setMaximumSize(new Dimension(180, 40));
        importButton.addActionListener(new GeneralUI.ImportButtonListener());
        rightPanel.add(Box.createVerticalStrut(10));
        rightPanel.add(importButton);

        exportButton = new JButton("导出题目");
        exportButton.setFont(font);
        exportButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        exportButton.setMaximumSize(new Dimension(180, 40));
        exportButton.addActionListener(new GeneralUI.ExportButtonListener());
        rightPanel.add(Box.createVerticalStrut(10));
        rightPanel.add(exportButton);



        JButton myButton = new JButton("GM模式");
        myButton.setFont(font);
        myButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        myButton.setMaximumSize(new Dimension(180, 40));
        myButton.addActionListener(new GeneralUI.MyButtonListener());
        rightPanel.add(Box.createVerticalStrut(10));
        rightPanel.add(myButton);

        JButton GoBackButton = new JButton("返回");
        GoBackButton.setFont(font);
        GoBackButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        GoBackButton.setMaximumSize(new Dimension(180, 40));
        GoBackButton.addActionListener(new GeneralUI.GoBackButtonListener());
        GoBackButton.setAlignmentY(Component.BOTTOM_ALIGNMENT);

        rightPanel.add(Box.createVerticalGlue());
        rightPanel.add(GoBackButton);


        add(rightPanel, BorderLayout.EAST);

        accuracyLabel = new JLabel("正确率：");
        accuracyLabel.setFont(font);
        add(accuracyLabel, BorderLayout.SOUTH);

        setVisible(true);
    }

    private class GradeLevelComboBoxListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            int gradeLevel = Integer.parseInt(Objects.requireNonNull(gradeLevelComboBox.getSelectedItem()).toString());
            if (gradeLevel ==1 || gradeLevel == 2) {
                questionsWithParenthesesField.setText("0");
            }
        }
    }

    private class GenerateButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                int totalQuestion = Integer.parseInt(totalQuestionField.getText());
                int questionsWithParentheses = Integer.parseInt(questionsWithParenthesesField.getText());
                int gradeLevel = Integer.parseInt(Objects.requireNonNull(gradeLevelComboBox.getSelectedItem()).toString());

                if (questionsWithParentheses > 10) {
                    JOptionPane.showMessageDialog(GeneralUI.this, "括号题数不能超过10", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                AddExerciseSetVO addExerciseSetVO = exerciseSetController.addExerciseSet(totalQuestion, questionsWithParentheses, gradeLevel);
                questions = addExerciseSetVO.getQuestions();
                exerciseSet = addExerciseSetVO.getExerciseSet();
                displayQuestions();
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(GeneralUI.this, "请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(GeneralUI.this, "生成题目失败", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void displayQuestions() {
        clearQuestions();

        questionPanels = new ArrayList<>();
        answerFields = new ArrayList<>();
        resultLabels = new ArrayList<>();

        Collections.shuffle(questions);

        for (Question question : questions) {
            JPanel questionPanel = new JPanel();
            questionPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
            questionPanel.setBackground(Color.CYAN);

            JLabel questionLabel = new JLabel("[" + (questions.indexOf(question) + 1) + "] " +question.getQuestionText() + "=");
            questionLabel.setFont(new Font("微软雅黑", Font.PLAIN, 20));
            questionPanel.add(questionLabel);

            JTextField answerField = new JTextField(2);
            answerField.setFont(new Font("微软雅黑", Font.PLAIN, 20));
            questionPanel.add(answerField);

            JLabel resultLabel = new JLabel("");
            resultLabel.setFont(new Font("微软雅黑", Font.PLAIN, 20));

            questionPanel.add(resultLabel);

            questionPanels.add(questionPanel);
            answerFields.add(answerField);
            resultLabels.add(resultLabel);

            ((JPanel) scrollPane.getViewport().getView()).add(questionPanel);
            ((JPanel) scrollPane.getViewport().getView()).add(Box.createVerticalStrut(20));
        }
        revalidate();
        repaint();
    }

    private class ClearButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            clearQuestions();
            revalidate();
            repaint();
        }
    }

    private void clearQuestions() {
        if (questionPanels != null) {
            JViewport viewport = scrollPane.getViewport();
            JPanel panel = (JPanel) viewport.getView();
            panel.removeAll();
            revalidate();
            repaint();

            questionPanels.clear();
            answerFields.clear();
            resultLabels.clear();
            accuracyLabel.setText("正确率：");
        }
    }

    private class CheckButtonListener implements ActionListener {
        private boolean hasMistake = false;
        @Override
        public void actionPerformed(ActionEvent e) {
            if (questions == null || questions.isEmpty()) {
                JOptionPane.showMessageDialog(GeneralUI.this, "请先生成题目", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            int correctCount = 0;

            for (int i = 0; i < questions.size(); i++) {
                Question question = questions.get(i);
                String answer = answerFields.get(i).getText();
                int expectedAnswer = question.getAnswer();
                if (answer.isEmpty()) {
                    resultLabels.get(i).setText("未作答");
                } else {
                    try {
                        int actualAnswer = Integer.parseInt(answer);
                        if (actualAnswer == expectedAnswer) {
                            resultLabels.get(i).setText("正确");
                            resultLabels.get(i).setForeground(Color.GREEN);
                            correctCount++;
                        } else {
                            resultLabels.get(i).setText("错误");
                            resultLabels.get(i).setForeground(Color.RED);

                            boolean recordSuccess = mistakeController.recordMistake(userId, question.getId(), actualAnswer);
                            if (!recordSuccess) {
                                JOptionPane.showMessageDialog(GeneralUI.this, "记录错误答案失败", "错误", JOptionPane.ERROR_MESSAGE);
                            } else {
                                hasMistake = true;
                            }
                        }
                    } catch (NumberFormatException ex) {
                        resultLabels.get(i).setText("无效答案");
                        resultLabels.get(i).setForeground(Color.RED);
                    }
                }
            }
            if (hasMistake) {
                JOptionPane.showMessageDialog(GeneralUI.this, "错误题目记录完成", "提示", JOptionPane.INFORMATION_MESSAGE);
            }
            if (isTimerRunning) {
                timer.stop();
                isTimerRunning = false;
                isEnalbeBth(isTimerRunning);
            }

            double accuracy = (double) correctCount / questions.size();
            exerciseSetController.setExerciseSetScore(exerciseSet.getId(), (int) (accuracy * 100));
            accuracyLabel.setText("正确率：" + (int)(accuracy * 100) + "%");
        }
    }

    private class ViewAnswersButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (questions == null || questions.isEmpty()) {
                JOptionPane.showMessageDialog(GeneralUI.this, "请先生成题目", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            for (int i = 0; i < questions.size(); i++) {
                Question question = questions.get(i);
                resultLabels.get(i).setText("正确答案：" + question.getAnswer());
            }
        }
    }

    public class TimerButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (questions == null) {
                JOptionPane.showMessageDialog(GeneralUI.this, "请先生成题目", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            String[] options = {"6分钟","10分钟", "30分钟", "60分钟", "90分钟"};
            String time = (String) JOptionPane.showInputDialog(GeneralUI.this, "请选择计时时间:", "提示", JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
            System.out.println("计时时间：" + time);
            if (time != null) {
                selectedMinutes = Integer.parseInt(time.replace("分钟", ""));
                int countDownSeconds = selectedMinutes * 60;
                timer = new Timer(1000, new TimerUpdateListener(countDownSeconds, timerLabel));
                timer.start();
                isTimerRunning = true;
                isEnalbeBth(isTimerRunning);
                updateTimerLabel(timerLabel, countDownSeconds);
            }
        }

        private static void updateTimerLabel(JLabel label, int secondsLeft) {
            int hours = secondsLeft / 3600;
            int minutes = (secondsLeft % 3600) / 60;
            int seconds = secondsLeft % 60;

            // 格式化时间为 HH:mm:ss
            label.setText(String.format("%02d:%02d:%02d", hours, minutes, seconds));
        }

        private class TimerUpdateListener implements ActionListener {
            private int remainingSeconds;
            private JLabel timerLabel;

            public TimerUpdateListener(int initialSeconds, JLabel timerLabel) {
                this.remainingSeconds = initialSeconds;
                this.timerLabel = timerLabel;
            }

            @Override
            public void actionPerformed(ActionEvent e) {
                if (remainingSeconds > 0) {
                    remainingSeconds--;
                    updateTimerLabel(timerLabel, remainingSeconds);

                    // 提醒用户剩余10分钟或5分钟
                    if (remainingSeconds == 600 || remainingSeconds == 300) { // 10分钟 = 600秒, 5分钟 = 300秒
                        Toolkit.getDefaultToolkit().beep(); // 播放系统提示音
                        startFlashEffect();
                    }
                } else {
                    // 计时结束，停止定时器
                    ((Timer) e.getSource()).stop();
                    JOptionPane.showMessageDialog(null, "时间到！", "提醒", JOptionPane.INFORMATION_MESSAGE);
                    isTimerRunning = false;
                    isEnalbeBth(isTimerRunning);
                    CheckButtonListener checkListener = new CheckButtonListener();
                    checkListener.actionPerformed(e);
                }
            }
        }
    }

    private void startFlashEffect() {
        if (flashTimer != null && flashTimer.isRunning()) {
            flashTimer.stop();
        }

        // 创建一个新的定时器用于闪烁效果
        flashTimer = new Timer(500, new ActionListener() {
            private boolean isRed = true;
            private int count = 0;

            @Override
            public void actionPerformed(ActionEvent e) {
                count++;
                if (count >= 6) { // 3秒内切换6次（每次500毫秒）
                    flashTimer.stop();
                    timerLabel.setForeground(Color.BLACK);
                    isFlashing = false;
                    return;
                }

                if (isRed) {
                    timerLabel.setForeground(Color.RED);
                } else {
                    timerLabel.setForeground(Color.BLACK);
                }
                isRed = !isRed;
            }
        });

        isFlashing = true;
        flashTimer.start();
    }


    private class MyButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {

//            totalQuestionField.setText("10");
//            gradeLevelComboBox.setSelectedItem("2");

            GeneralUI.GenerateButtonListener listener = new GeneralUI.GenerateButtonListener();
            listener.actionPerformed(e);

            for (int i = 0; i < questions.size(); i++) {
                Question question = questions.get(i);
                String answer = String.valueOf(question.getAnswer());
                answerFields.get(i).setText(answer);
            }

//            GeneralUI.CheckButtonListener checkListener = new GeneralUI.CheckButtonListener();
//            checkListener.actionPerformed(e);

            JOptionPane.showMessageDialog(GeneralUI.this, "已自动填入正确答案", "提示", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    private class GoBackButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            int result = JOptionPane.showConfirmDialog(GeneralUI.this, "确定要退出吗？", "提示", JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                if (isTimerRunning) {
                    timer.stop();
                }
                dispose();
                new RouterUI();
            } else if (result == JOptionPane.NO_OPTION) {
                return;
            }
        }
    }

    private void isEnalbeBth(boolean isTimerRunning) {
        if (isTimerRunning) {
            totalQuestionField.setEnabled(false);
            questionsWithParenthesesField.setEnabled(false);
            gradeLevelComboBox.setEnabled(false);
            generateButton.setEnabled(false);
            viewAnswersButton.setEnabled(false);
            clearButton.setEnabled(false);
            timerButton.setEnabled(false);
            importButton.setEnabled(false);
            exportButton.setEnabled(false);
        } else {
            timerLabel.setText("--:--:--");
            totalQuestionField.setEnabled(true);
            questionsWithParenthesesField.setEnabled(true);
            gradeLevelComboBox.setEnabled(true);
            generateButton.setEnabled(true);
            viewAnswersButton.setEnabled(true);
            clearButton.setEnabled(true);
            timerButton.setEnabled(true);
            importButton.setEnabled(true);
            exportButton.setEnabled(true);
        }
    }


    private class ImportButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("导入题目");
            questions = new ArrayList<>();
            JFileChooser fileChooser = new JFileChooser();
            int returnValue = fileChooser.showOpenDialog(GeneralUI.this);
            if (returnValue == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();
                System.out.println("Selected file: " + selectedFile.getAbsolutePath());
                try (BufferedReader reader = new BufferedReader(new FileReader(selectedFile))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        String[] parts = line.split(",");
                        Question question = Question.builder()
                                .questionText(parts[0])
                                .answer(Integer.parseInt(parts[1]))
                                .hasParentheses(parts[0].contains("("))
                                .build();
                        questions.add(question);
                    }
                    if (questions.isEmpty()) {
                        JOptionPane.showMessageDialog(GeneralUI.this, "文件内习题为空，请重新选择文件", "错误", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                    AddExerciseSetVO addExerciseSetVO = exerciseSetController.importQuestions(questions);
                    if (addExerciseSetVO != null) {
                        questions = addExerciseSetVO.getQuestions();
                        exerciseSet = addExerciseSetVO.getExerciseSet();
                        displayQuestions();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

        }
    }

    private class ExportButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("导出题目");
            if (questions.isEmpty()) {
                JOptionPane.showMessageDialog(GeneralUI.this, "请先生成题目", "提示", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            JFileChooser fileChooser = new JFileChooser();
            int returnValue = fileChooser.showSaveDialog(GeneralUI.this);
            if (returnValue == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();
                try (BufferedWriter writer = new BufferedWriter(new FileWriter(selectedFile))) {
                    for (Question question : questions) {
                        writer.write(question.getQuestionText() + "," + question.getAnswer());
                        writer.newLine();
                    }
                    System.out.println("题目已导出到文件：" + selectedFile.getAbsolutePath());
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }


//    public static void main(String[] args) {
//        new GeneralUI();
//    }

}
